package com.shujia.custom.udtf;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MyUDTFDemo1 extends GenericUDTF {
    /*
       初始化，可以在这个方法中创建一些连接对象
       指定返回的列数据类型和列名

       输入：M1001#xiaohu#S324231212,lkd#M1002#S2543412432,S21312312412#M1003#bfy

       输出：
            1001 xiaohu 324231212
            1002 lkd 2543412432
            1003 bfy 21312312412
     */
    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {
        //创建两个集合，这两个集合是一一对应的关系
        //一个是列名的集合
        ArrayList<String> colNameList = new ArrayList<>();
        colNameList.add("id");
        colNameList.add("name");
        colNameList.add("card_id");
        //另一个是列数据类型的集合
        ArrayList<ObjectInspector> colTypeList = new ArrayList<>();
        colTypeList.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        colTypeList.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        colTypeList.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        //将列名集合和列数据类型集合对应返回
        return ObjectInspectorFactory.getStandardStructObjectInspector(colNameList,colTypeList);
    }

    /*
            核心方法
            将传进的一行数据，进行处理，返回
         */
    @Override
    public void process(Object[] args) throws HiveException {
        //创建一个数组，接收每次的一行三列数据
        String[] strings = new String[3];

        //args：接收传进的一行多列数据，每一列是数组的一个元素
        //M1001#xiaohu#S324231212,lkd#M1002#S2543412432,S21312312412#M1003#bfy
        String info = args[0].toString();
        String[] infos = info.split(",");
        for (String stuInfo : infos) {
            String[] stuInfos = stuInfo.split("#");
            for (String stu : stuInfos) {
                if(stu.startsWith("M")){
                    strings[0] = stu.substring(1);
                }else if(stu.startsWith("S")){
                    strings[2] = stu.substring(1);
                }else {
                    strings[1] = stu;
                }
            }

            //调用收集器方法，将处理好的一行数据进行返回
            forward(strings);
        }
    }

    /*
        关闭一些在initialize方法中创建的对象
     */
    @Override
    public void close() throws HiveException {
        //...
    }
}
